<template>
  <div class="container">
    <div class="box">
      <h1>登录</h1>
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="70px">
        <el-form-item prop="username">
          <label>用户名：</label>
          <el-input v-model="userForm.username" type="text" prefix-icon="el-icon-user-solid" placeholder="请输入用户名："></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <label>密码：</label>
          <el-input v-model="userForm.password" type="password" prefix-icon="el-icon-lock" placeholder="请输入密码：" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      userForm: {
        username: '',
        password: ''
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('/login', this.userForm)
        console.log(res)
        if (res.status !== 200) return this.$message.error('登录失败！')
        this.$message.success('登陆成功！')
        /*
          将登陆成功之后的 token ，保存到客户端的 sessionStorage 中。
              1. 项目中除了登录之外的其他 API 接口，必须在登录之后才能访问。
              2. token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中。
         */
        window.sessionStorage.setItem('token', res.data.token)
        this.$store.state.auth = res.data.auth
        this.$store.state.activePath = '/home'
        // 通过编程式导航跳转到后台主页，路由地址是 /home 。
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .container{
    width: 100%;
    height: 100%;
    text-align: center;
    background: url("../assets/image/bc.jpg") no-repeat;
    background-size: cover;
    overflow: hidden;
    .box{
      width: 500px;
      height: 600px;
      margin: 100px auto 0 auto;
      background-color: rgba(0, 0, 0, 0.3);
      overflow: hidden;
      border-radius: 20px;
      h1{
        font-size: 50px;
        color: #fff;
        margin-top: 50px;
      }
    }
  }
  .el-form{
    margin-top: 40px;
    .el-form-item{
      margin-left: 20px;
      width: 400px;
      display: flex;
      justify-content: space-between;
      label{
        display: block;
        float: left;
        font-size: 25px;
        color: #fff;
      }
      .el-input{
        margin: 35px auto;
        width: 330px;
      }
      .el-button{
        width: 100px;
        height: 50px;
        font-size: 18px;
      }
    }
  }
</style>
